package com.cet.algorithm.回溯.n皇后问题;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @program: cet-practice
 * @description: N皇后问题
 * @author: 陈恩涛
 * @create: 2023-06-04 09:51
 **/
public class LC51 {

    List<List<String>> result = new LinkedList<>();

    public List<List<String>> solveNQueens(int n) {
        char[][] chessboard = new char[n][n];
        for (char[] chars : chessboard) {
            Arrays.fill(chars, '.');
        }
        backTracing(n, 0, chessboard);
        return result;
    }

    public void backTracing(int n, int row, char[][] chessboard) {


        // 递归终止条件
        if (row == n) {
            result.add(array2List(chessboard));
            return;
        }

        // 单层递归逻辑
        for (int i = 0; i < n; i++) {
            if (!isValidPosition(chessboard, row, i)) {
                continue;
            }

            chessboard[row][i] = 'Q';
            backTracing(n, row + 1, chessboard);
            chessboard[row][i] = '.';
        }
    }

    private List<String> array2List(char[][] array) {
        List<String> list = new LinkedList<>();

        for (char[] chars : array) {
            list.add(String.copyValueOf(chars));
        }

        return list;
    }

    /**
     * 判断当前皇后位置是否与其他皇后位置冲突
     * @param chessboard 棋盘
     * @param row 行
     * @param colum 列
     * @return 位置是否合适
     */
    private boolean isValidPosition(char[][] chessboard, int row, int colum) {

        int n = chessboard.length;

        // 同行位置不用判断，遍历已经能保证了

        // 同列
        for (int i = 0; i < row; i++) {
            if (chessboard[i][colum] == 'Q') {
                return false;
            }
        }

        // 45度角
        for (int i = row - 1, j = colum + 1; i >= 0 && j < n; i--, j++) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }

        // 135度角
        for (int i = row - 1, j = colum - 1; i >= 0 && j >= 0; i--, j--) {
            if (chessboard[i][j] == 'Q') {
                return false;
            }
        }

        return true;

    }

    public static void main(String[] args) {
        LC51 lc51 = new LC51();
        System.out.println(lc51.solveNQueens(4));
    }
}
